package com.mysns.web.controller;

import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.google.code.kaptcha.Producer;

/**
 * 利用 kaptcha 来生成验证码图片.
 * 
 * @author zhouych
 */
@Controller
@RequestMapping(value = "/kaptcha")
public class KaptchaController {

	/**
	 * kaptcha的生成器, 具体配置见 "applicationContext-kaptcha.xml"
	 */
	@Autowired
	private Producer producer;
	
	@RequestMapping(value = "/image")
	public ModelAndView hadleRequest(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		
		// 设置工作模式为headless
		System.setProperty("java.awt.headless", "true");
		
		// 设置页面不缓存
		response.setHeader("Pragma", "No-cache");
	    response.setHeader("Cache-Control", "no-cache");
	    response.setDateHeader("Expires", 0);
		response.setContentType("image/jpeg");
		
		// 给图片创建文字验证码
		String capText = producer.createText();
		
		// 将验证码存入session
		request.getSession().setAttribute(
				com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY, capText);
		
		// 在内存中创建图片
		BufferedImage bufferedImg = producer.createImage(capText);
		
		//输出图象到页面
	    ImageIO.write(bufferedImg, "JPEG", response.getOutputStream());
	    
		return null;
	}
}
